package dao.impl;


import dao.OrderItemDao;
import domain.Order;
import domain.OrderItem;
import domain.Product;
import org.apache.commons.dbutils.QueryRunner;
import util.DataSourceUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderItemDaoImpl implements OrderItemDao {
    public List<OrderItem> findOrderItemByOrder(Order order) throws SQLException {
        String sql = "select * from orderitem, products where orderitem.product_id = products.id and orderitem.order_id = ?";
        QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
        // 返回订单项链表集合
        return runner.query(sql, rs -> {
            // 创建订单项集合链表
            List<OrderItem> orderItems = new ArrayList<>();
            // 循环遍历订单项和商品信息
            while (rs.next()) {
                // 创建订单项对象，将从数据库中查询到的订单项属性添加到订单项对象中
                OrderItem orderItem = new OrderItem();
                orderItem.setBuyNum(rs.getInt("orderitem.buynum"));
                orderItem.setOrder(order);
                // 创建商品对象，将从数据库中查询到的商品属性添加到订单项对象中
                Product product = new Product();
                product.setId(rs.getString("products.id"));
                product.setName(rs.getString("products.name"));
                product.setPrice(rs.getDouble("products.price"));
                product.setCategory(rs.getString("products.category"));
                product.setPnum(rs.getInt("products.pnum"));
                product.setImgurl(rs.getString("products.imgurl"));
                product.setDescription(rs.getString("products.description"));
                // 将商品对象添加到订单项对象中
                orderItem.setProduct(product);
                // 将订单项对象添加到订单项链表集合中
                orderItems.add(orderItem);
            }
            return orderItems;
        }, order.getId());
    }

    @Override
    public int removeOrderItemById(String id) throws SQLException {
        String sql = "delete from orderitem where order_id = ?";
        QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
        return runner.update(sql, id);
    }
}
